<?php

namespace app\controller;

use app\BaseController;
use app\model\City;
use app\model\Study;
use app\utils\CharacterUtils;
use app\utils\FilesUtils;
use app\validate\CityValidate;
use app\validate\FileValidate;
use app\validate\StudyValidate;
use think\App;
use think\exception\ValidateException;

class StudyController extends BaseController
{

    /**
     * @var Study
     */
    private $dao;

    public function __construct(App $app)
    {
        $this->dao = new Study();
        parent::__construct($app);
    }

    public function getList(){
        $keyword = $this->request->param('keyword', '');

        return $this->returnJson($this->dao->where('q','like', '%'.$keyword.'%')->select());
    }

    public function addOrUpdate(){
        $is_add = $this->request->post('is_add', 1);
        $q = $this->request->post('q');
        $a = $this->request->post('a');
        $type = $this->request->post('type');
        $file = $this->request->file('file');

        if (!$is_add){
            $id = $this->request->post('id');
            $updateArr = [];
            if (!empty($file)){
                Validate(FileValidate::class)
                    ->scene('file')
                    ->check(['file'=>$file]);

                $fliesUtils = new FilesUtils();
                $save = $fliesUtils->save('study', $file);
                $updateArr['file_url'] = env('app.storageaddress').$save['url'];
            }

            empty($q) || $updateArr['q'] = $q;
            empty($a) || $updateArr['a'] = $a;
            empty($type) || $updateArr['type'] = $type;

            $this->dao->where('id', $id)->update($updateArr);
            return $this->returnJson($this->dao->find($id));
        }

        if(!empty($file)){
            Validate(FileValidate::class)
                ->scene('file')
                ->check(['file'=>$file]);
            $fliesUtils = new FilesUtils();

            $url = env('app.storageaddress').$fliesUtils->save('study', $file)['url'];
        }else{
            $url = '';
        }


        Validate(StudyValidate::class)
            ->scene('add')
            ->check(['q'=>$q ,'a'=>$a ,'type'=>$type]);









        return $this->returnJson($this->dao->create([
            'q'=>$q,
            'a'=>$a,
            'type'=>$type,
            'file_url'=>$url,
        ]));
    }

    public function delete(Study $study){
        return $this->returnJson($this->dao->destroy($study->id));
    }

}